<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script type="text/javascript">
        // 数组reduce 累加
        function sum(arr) {
            return arr.reduce((total, curr) => {
                return total += curr
            }, 0)
        }
        console.log(sum([1, 2, 3, 4]));
   /*   三、map,forEach区别
            1、map速度比foreach快
            2、map会返回一个新数组，不对原数组产生影响,foreach不会产生新数组，foreach返回undefined
            3、map因为返回数组所以可以链式操作，foreach不能
            4, map里可以用return ,而foreach里用return不起作用，foreach不能用break，会直接报错 
            */
        function sum1(arr) {
            let num = 0;
            arr.map(item =>{
                num += item;
            })
            return num;
        }
        console.log(sum1([1,2,3,4,50,5]));

        function sum2(arr){
            let num = 0;
            arr.forEach(item=>{
                num+= item;
            })
            return num;
        }
        console.log(sum2([1,2,3,4,50,5]));
   
        function sum3(arr){
            let num = 0;
            for(let i = 0; i < arr.length; i++){
                num += arr[i];
            }
            return num;
        }
        console.log(sum3([1,2,3]));
    </script>
</body>

</html>